/*
 * RoleService.java
 *
 * Copyright 2012 the original author or authors(ninglong).
 *
 * Licensed under the web-geek, Version 1.0 (the "License");
 *
 */
package org.geek.app.role.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.geek.app.role.service.IRoleService;
import org.geek.core.base.AppConstants;
import org.geek.core.bean.ExtTree;
import org.geek.core.mybatis.domain.Criteria;
import org.geek.core.mybatis.domain.Role;
import org.geek.core.mybatis.mapper.RoleMapper;
import org.springframework.stereotype.Service;

@Service
public class RoleService implements IRoleService {

	@Resource
	private RoleMapper roleMapper;
	
	@Override
	public int countRoleByCriteria(Criteria criteria) {
		return roleMapper.countRoleByCriteria(criteria);
	}
	
	@Override
	public List<Role> getRoleByCriteria(Criteria criteria) {
		return roleMapper.getRoleByCriteria(criteria);
	}
	
	@Override
	public List<ExtTree> getRoles2Tree(int userId) {
		Criteria criteria = new Criteria();
		List<Role> list = null;
		if(userId==0){
			list = roleMapper.getRoleByCriteria(criteria);
		}else{
			list = roleMapper.getRoles2User(userId);
		}
		List<ExtTree> menus = new ArrayList<ExtTree>();
		for(Role role : list){
			ExtTree menu = new ExtTree();
			menu.setId(role.getRoleId());
			menu.setParentId(0);
			menu.setName(role.getRoleName());
			menus.add(menu);
		}
		return menus;
	}
	
	@Override
	public int addRole(Role role) {
		return roleMapper.addRole(role);
	}
	
	public int modRole(Role role) {
		return roleMapper.modRole(role);
	}

	public int delRoleByRoleId(int roleId) {
		int i = roleMapper.delRoleByRoleId(roleId);
		i = i + roleMapper.delRoleAndUserByRoleId(roleId);//删除角色后,将t_user_role表中与该角色相关的数据删除
		return i;
	}

	@Override
	public int saveAuth(int roleId, int moduleId, String[] actionIds) {
		Criteria criteria = new Criteria();
		criteria.put("roleId", roleId);
		int i=0;
		for(String actionId :actionIds){//先删除权限
			criteria.put("resouceId", Integer.valueOf(actionId));
			roleMapper.delAuthByRoleIdAndResouceId(criteria);
			if(i==0){
				criteria.put("authType",AppConstants.Auth.menu);
			}else{
				criteria.put("authType",AppConstants.Auth.button);
			}
			roleMapper.saveAuth(criteria);
			i++;
		}
		return 0;
	}
}